package com.zjj.sc.helloworld.controller;

import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.zjj.sc.helloworld.dao.UserRepository;
import com.zjj.sc.helloworld.dto.User;

@RestController
public class UserController {
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	UserRepository userRepository;
	
	@GetMapping("/{id}")
	public User findById(@PathVariable Long id) {
		
		logger.info("start user test ----------------------------------");
		
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		if(principal instanceof UserDetails) {
			UserDetails user = (UserDetails) principal;
			Collection<? extends GrantedAuthority> collection = user.getAuthorities();
			for(GrantedAuthority c : collection) {
				logger.info("login user info : username = {} , role = {}", user.getUsername(), c.getAuthority());
			}
		}
		
		User user = this.userRepository.findOne(id);
		return user;
	}
	

}
